<?php

namespace App\Amqp\Consumer;

use App\Constants\FemaleKeepPushCode;
use App\Model\FemaleKeepPush;
use App\Model\Gift;
use App\Model\GiftBatchLog;
use App\Model\GiftLog;
use App\Model\Message;
use App\Model\Setting\SettingAppHidden;
use App\Model\User;
use App\Model\UserProfile;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\Type;
use Hyperf\DbConnection\Db;
use PhpAmqpLib\Message\AMQPMessage;
use Hyperf\Amqp\Result;

/**
 * @Consumer(exchange="FemalePushGift", routingKey="FemalePushGift", queue="FemalePushGift.send", name ="FemalePushGiftConsumer", nums=1)
 */
class FemalePushGiftConsumer extends ConsumerMessage
{
    /**
     * @var string
     */
    protected $type = Type::DIRECT;

    /**
     * 结算单独公会
     * @param $data
     * @param AMQPMessage $message
     * @return string
     */
    public function consumeMessage($data, AMQPMessage $message): string
    {
        try {
            if (!$data['user_id']) {
                log_error('FemalePushGiftConsumer:error:NoUserId:data:' . json_encode($data));
                return Result::ACK;
            }

            $user = User::getUser($data['user_id']);
            if (empty($user)) {
                return Result::ACK;
            }

            if ($user->status != 0){
                log_error('FemalePushGiftConsumer:error:UserStatusIncorrect:data:' . json_encode($user->toArray()));
                return Result::ACK;
            }

            $this->userId = $data['user_id'];
            //分配的礼物信息
            $this->giftInfo = Gift::getInfo(FemaleKeepPushCode::GIFT_ID);

            $this->count = FemaleKeepPushCode::SINGLE_MAXIMUM;

            //如果女用户处于屏蔽渠道跳出
            if (SettingAppHidden::checkModuleHiddenByUser(
                    $this->userId,
                    $user->app_id,
                    $user->app_version,
                    $user->cur_channel,
                    SettingAppHidden::FUNC_PUSH
                ) == 1
            ) {
                log_info('FemalePushGiftConsumer:info:shield:data:' . json_encode($data));
                return Result::ACK;
            }

            //如果没有大于5000财富值的跳出
            $userIds = UserProfile::getUserIdByRichValue(FemaleKeepPushCode::RICH_VALUE);
            $userIds = array_diff($userIds,[env('KEFU_UID',7),env('KEFU_UID2',8)]);
            if (empty($userIds)) {
                log_info('FemalePushGiftConsumer:info:no:richValueData:' . json_encode($data));
                return Result::ACK;
            }

            //女用户超过50条跳出
            $femaleKeepPushModel = new FemaleKeepPush();
            $pushedMaleIds = $femaleKeepPushModel->getMaleIdsByUserId($this->userId);
            if (count($pushedMaleIds) >= FemaleKeepPushCode::MAX_PUSH) {
                log_info('FemalePushGiftConsumer:info:max:limit:' . json_encode($data));
                return Result::ACK;
            }

            //如果超额就减少
            if (FemaleKeepPushCode::MAX_PUSH - count($pushedMaleIds) < $this->count){
                $this->count = FemaleKeepPushCode::MAX_PUSH - count($pushedMaleIds);
            }

            //如果没有可推送的用户跳出
            $canPushMaleIds = array_diff($userIds, $pushedMaleIds);
            if (empty($canPushMaleIds)) {
                log_info('FemalePushGiftConsumer:info:no:pushData:' . json_encode($data));
                return Result::ACK;
            }

            //如果可以推送的没有这么多
            if (count($canPushMaleIds) < $this->count){
                $this->count = count($canPushMaleIds);
            }

            //随机抽取足量的
            $pushUserIds = [];
            foreach (array_rand($canPushMaleIds, $this->count) as $one) {
                $pushUserIds[] = $canPushMaleIds[$one];
            }
            //顺序抽取
//            sort($canPushMaleIds);
//            $pushUserIds = array_slice($canPushMaleIds,0,$this->count);

            //没有抽取到用户直接跳出
            if (empty($pushUserIds)) {
                log_info('FemalePushGiftConsumer:info:no:pushData2:' . json_encode($data));
                return Result::ACK;
            }

            //开始推送
            $this->doSend(
                $pushUserIds
            );

            return Result::ACK;
        } catch (\Throwable $exception) {
//            var_dump($exception->getMessage());
            log_error('FemalePushGiftConsumer:error:ERROR:guild_id:' .$exception->getMessage());
            Db::rollBack();
            return Result::REQUEUE;
        }

    }


    /**
     * 执行
     * @param array $canPushUserIds
     * @return void
     */
    private function doSend(array $canPushUserIds): void
    {
        if (empty($canPushUserIds)) {
            return;
        }

        $pushUserIds = [];
        foreach ($canPushUserIds as $maleId) {
            //添加送礼记录
            $record = GiftLog::addSysGiftRecord(
                $maleId,
                $this->userId,
                GiftLog::FROM_SYS_REGISTER_FEMALE,
                true,
                $this->giftInfo,
                FemaleKeepPushCode::GIFT_EXPIRATION_TIME
            );

            $record && array_push($pushUserIds, $maleId);

            GiftBatchLog::create([
                'user_id' => $maleId,
                'receive_user_id' => json_encode([$this->userId]),
                'send_user_id' => '',
                'gift_id' => $this->giftInfo['id'],
                'gift_type' => Gift::TYPE_FEMALE_REGISTER,
                'flag' => 1,
            ]);
            FemaleKeepPush::create([
                'user_id' => $this->userId,
                'male_id' => $maleId,
            ]);

            Message::sendGift($this->userId, $maleId, $this->giftInfo, true,0,'',true);
        }
    }
}